/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AssociadoDialog.java
 *
 * Created on 21/10/2011, 13:26:50
 */
package br.com.seguradora.view.dialog;

import br.com.seguradora.exception.InputValidationException;
import br.com.seguradora.exception.PersistenciaException;
import br.com.seguradora.model.Associado;
import br.com.seguradora.model.Telefone;
import br.com.seguradora.model.constant.EstadoCivil;
import br.com.seguradora.service.AssociadoService;
import br.com.seguradora.view.ErrorsList;
import br.com.seguradora.view.StateEntityWindow;
import br.com.seguradora.view.UserError;
import com.towel.time.DateUtils;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;

/**
 *
 * @author Diego
 */
public class AssociadoDialog extends javax.swing.JDialog {

    private Associado associado;
    private final static String titleWindow = "Associado";
    private StateEntityWindow stateEntity;
    
    public AssociadoDialog(java.awt.Frame parent, boolean modal, StateEntityWindow stateEntity, Associado associado) {
        super(parent, modal);
        initComponents();
        this.stateEntity = stateEntity;
        setTitle(titleWindow + stateEntity);
        setAssociado(associado);
        organizeWindow();
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cabecalhoPanel = new br.com.seguradora.view.panel.CabecalhoPanel();
        jLabel1 = new javax.swing.JLabel();
        nomeField = new javax.swing.JTextField();
        nomeErrorLabel = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        estadoCivilCombo = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        dataNascField = new javax.swing.JFormattedTextField();
        dataNascErrorLabel = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        cpfField = new javax.swing.JFormattedTextField();
        jLabel5 = new javax.swing.JLabel();
        identidadeField = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        orgExpField = new javax.swing.JTextField();
        cpfErrorLabel = new javax.swing.JLabel();
        identidadeErrorLabel = new javax.swing.JLabel();
        enderecoPanel = new br.com.seguradora.view.panel.EnderecoPanel();
        telefonesPanel = new br.com.seguradora.view.panel.TelefonesPanel();
        observacaoPanel = new br.com.seguradora.view.panel.ObservacaoPanel();
        jSeparator1 = new javax.swing.JSeparator();
        confirmarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Nome:");

        nomeErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        jLabel3.setText("Estado civil:");

        estadoCivilCombo.setModel(new DefaultComboBoxModel(EstadoCivil.values()));

        jLabel6.setText("Data de nasc.:");

        try {
            dataNascField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        dataNascField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        dataNascErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        jLabel4.setText("CPF:");

        try {
            cpfField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        cpfField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);

        jLabel5.setText("Identidade:");

        jLabel8.setText("Orgão exp.:");

        cpfErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        identidadeErrorLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/exclamation.png"))); // NOI18N

        confirmarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/accept.png"))); // NOI18N
        confirmarButton.setText("Confirmar");
        confirmarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmarButtonActionPerformed(evt);
            }
        });

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/seguradora/resources/cross.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 368, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel5))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createSequentialGroup()
                                    .addContainerGap()
                                    .addComponent(jLabel3))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                    .addGap(74, 74, 74)
                                    .addComponent(jLabel1))
                                .addGroup(layout.createSequentialGroup()
                                    .addContainerGap()
                                    .addComponent(jLabel4))))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(nomeField, javax.swing.GroupLayout.PREFERRED_SIZE, 399, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(estadoCivilCombo, 0, 100, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(dataNascField, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(cpfField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(identidadeField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE))
                                .addGap(4, 4, 4)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(identidadeErrorLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                                        .addComponent(jLabel8)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(orgExpField, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(cpfErrorLabel))
                                .addGap(47, 47, 47)))
                        .addGap(4, 4, 4)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(dataNascErrorLabel)
                            .addComponent(nomeErrorLabel)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(enderecoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(32, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(observacaoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(telefonesPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(123, 123, 123)
                .addComponent(confirmarButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelarButton)
                .addContainerGap(261, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(cabecalhoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nomeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nomeErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3)
                                .addComponent(estadoCivilCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(dataNascField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel6))
                            .addComponent(dataNascErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(cpfField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(cpfErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel5)
                        .addComponent(identidadeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(orgExpField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel8))
                    .addComponent(identidadeErrorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(enderecoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(telefonesPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(observacaoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(confirmarButton)
                    .addComponent(cancelarButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void confirmarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_confirmarButtonActionPerformed
        try {
            validateUserInput();
            AssociadoService associadoService = new AssociadoService();
            Associado associado = getAssociado();
            if (getStateEntity() == StateEntityWindow.NEW) {
                associadoService.inserir(associado);
            } else if (getStateEntity() == StateEntityWindow.UPDATE) {
                associadoService.atualizar(associado);
            }
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, "Erros foram encontrados.", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
            ErrorsList errorsList = ivex.getErrorsList();
            for (Iterator<UserError> it = errorsList.iterator(); it.hasNext();) {
                UserError userError = it.next();
                showErrorLabel(userError);
            }
        }
}//GEN-LAST:event_confirmarButtonActionPerformed

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
}//GEN-LAST:event_cancelarButtonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println(ex);
        }
        //</editor-fold>
        
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                AssociadoDialog dialog = new AssociadoDialog(new javax.swing.JFrame(), true, StateEntityWindow.NEW, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private br.com.seguradora.view.panel.CabecalhoPanel cabecalhoPanel;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JButton confirmarButton;
    private javax.swing.JLabel cpfErrorLabel;
    private javax.swing.JFormattedTextField cpfField;
    private javax.swing.JLabel dataNascErrorLabel;
    private javax.swing.JFormattedTextField dataNascField;
    private br.com.seguradora.view.panel.EnderecoPanel enderecoPanel;
    private javax.swing.JComboBox estadoCivilCombo;
    private javax.swing.JLabel identidadeErrorLabel;
    private javax.swing.JTextField identidadeField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel nomeErrorLabel;
    private javax.swing.JTextField nomeField;
    private br.com.seguradora.view.panel.ObservacaoPanel observacaoPanel;
    private javax.swing.JTextField orgExpField;
    private br.com.seguradora.view.panel.TelefonesPanel telefonesPanel;
    // End of variables declaration//GEN-END:variables

    private void organizeWindow() {
        if (getStateEntity() == StateEntityWindow.NEW) {
            cabecalhoPanel.setBloqueado(true);
            cabecalhoPanel.isEnabledComponentBloqueado(false);
            telefonesPanel.setTelefonesList(new ArrayList<Telefone>());
        }
        isShowErrorsLabel(false);
    }

    public StateEntityWindow getStateEntity() {
        return stateEntity;
    }

    private void validateUserInput() throws InputValidationException {
        isShowErrorsLabel(false);
        ErrorsList errorsList = new ErrorsList();
        if (nomeField.getText().isEmpty()) {
            errorsList.addError(new UserError(nomeErrorLabel, "O nome do associado não foi informado."));
        }
        if(!DateUtils.isValidDate(dataNascField.getText())) {
            errorsList.addError(new UserError(dataNascErrorLabel, "A data de nascimento do associado não foi informada corretamente."));
        }
        if(cpfField.getText().equals("   .   .   -  ")) {
            errorsList.addError(new UserError(cpfErrorLabel, "O cpf do associado não foi informado."));
        }
        if(identidadeField.getText().isEmpty()) {
            errorsList.addError(new UserError(identidadeErrorLabel, "A identidade do associado não foi informada."));
        }
        if(enderecoPanel.getEndereco() == null) {
            errorsList.addError(new UserError(enderecoPanel.getLogradouroErrorLabel(), "O endereço do associado não foi informado."));
        }
        if (errorsList.countErrors() > 0) {
            throw new InputValidationException(errorsList);
        }
    }

    private void isShowErrorsLabel(boolean show) {
        nomeErrorLabel.setVisible(show);
        dataNascErrorLabel.setVisible(show);
        cpfErrorLabel.setVisible(show);
        identidadeErrorLabel.setVisible(show);
        enderecoPanel.getLogradouroErrorLabel().setVisible(show);
    }
    
    private void showErrorLabel(UserError userError) {
        userError.getLabel().setVisible(true);
    }
    
    private Associado getAssociado() {
        if(associado == null) {
            this.associado = new Associado();
        }
        associado.setBloqueado(cabecalhoPanel.isBloqueado());
        associado.setNome(nomeField.getText().toUpperCase());
        associado.setEstadoCivil((EstadoCivil) estadoCivilCombo.getSelectedItem());
        associado.setDataNascimento(DateUtils.parseDate(dataNascField.getText()));
        associado.setCpf(cpfField.getText());
        associado.setRg(identidadeField.getText());
        associado.setOrgExp(orgExpField.getText().toUpperCase());
        associado.setEndereco(enderecoPanel.getEndereco());
        associado.setTelefonesList(telefonesPanel.getTelefonesList());
        associado.setObservacao(observacaoPanel.getObservacao());
        return associado;
    }
    
    private void setAssociado(Associado associado) {
        if(associado == null) {
            return;
        }
        this.associado = associado;
        cabecalhoPanel.setCodigo(associado.getId());
        cabecalhoPanel.setBloqueado(associado.isBloqueado());
        nomeField.setText(associado.getNome());
        estadoCivilCombo.setSelectedItem(associado.getEstadoCivil());
        dataNascField.setText(DateUtils.format(associado.getDataNascimento()));
        cpfField.setText(associado.getCpf());
        identidadeField.setText(associado.getRg());
        orgExpField.setText(associado.getOrgExp());
        enderecoPanel.setEndereco(associado.getEndereco());
        telefonesPanel.setTelefonesList(associado.getTelefonesList());
        observacaoPanel.setObservacao(associado.getObservacao());
    }
    
    public Associado objetoAssociado() {
        return associado;
    }
    
    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                cancelarButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }
}
